#encoding:utf8

import tornado
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler
from tornado import gen

app = tornado.web.Application()


service_map = {}
service_deadline = {}


class ServerFinderHandler(RequestHandler):
    @tornado.web.asynchronous
    @gen.coroutine
    def get(self):
        service = self.get_argument('service')

        global service_map
        hosts = ''
        if service in service_map:
            hosts = ','.join(service_map[service])
        self.finish(hosts)


class ServerRegisterHandler(RequestHandler):
    @tornado.web.asynchronous
    @gen.coroutine
    def get(self):
        service_host = self.get_argument('service')
        todo = self.get_argument('todo')
        service, host = service_host.split('@')

        global service_map
        if service not in service_map:
            service_map[service] = []
        if todo == 'register':
            if host not in service_map[service]:
                service_map[service].append(host)
            # 如果该服务有在定时移除中， 移除该定时任务
            if service_host in service_deadline:
                IOLoop.current().remove_timeout(service_deadline[service_host])
            # 重新注册 15s 后移除该服务
            service_deadline[service_host] = IOLoop.current().add_timeout(IOLoop.current().time() + 15, remove_host,
                                                                          service, host)
        self.finish("success")


def remove_host(service, host):
    global service_map
    service_map[service].remove(host)

app.add_handlers(r'.*$', [('^/server-finder/$', ServerFinderHandler)])
app.add_handlers(r'.*$', [('^/server-register/$', ServerRegisterHandler)])

if __name__ == '__main__':
    app.listen(43330, "127.0.0.1", xheaders=True)
    IOLoop.instance().start()
